package com.xm.share.service.impl;

import com.xm.share.model.vo.UserInfoDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xm.share.common.utils.MessageModel;
import com.xm.share.mapper.UserInfoMapper;
import com.xm.share.model.UserInfo;
import com.xm.share.model.vo.SystemReportDto;
import com.xm.share.service.UserService;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfo findByName(String userName) throws Exception {
        return userInfoMapper.findByName(userName);
    }

    @Override
    public MessageModel register(UserInfo userInfo) throws Exception {
        MessageModel model = new MessageModel(false);
        UserInfo info = findByName(userInfo.getUserName());
        if (info != null) {
            model.setMsg("用户名重复");
        } else {
            userInfoMapper.insert(userInfo);
            model.setSuccess(true);
        }
        return model;
    }

    @Override
    public SystemReportDto getSystemReport() throws Exception {
        return userInfoMapper.getSystemReport();
    }

    @Override
    public void updateUserInfo(UserInfo userInfo) throws Exception {
        userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }

    @Override
    public UserInfo findById(Long userId) throws Exception {
        return userInfoMapper.selectByPrimaryKey(userId);
    }

    @Override
    public List<UserInfoDto> getUserinfoDtoList(int pageNo, int pageSize) throws Exception {
        if (pageNo <= 0) {
            pageNo = 1;
        }
        int begin = (pageNo - 1) * pageSize;
        int end = pageNo * pageSize;

        List<UserInfoDto> userinfoDtoList = userInfoMapper.getUserinfoDtoList(begin, end);

        for (UserInfoDto userInfoDto : userinfoDtoList) {
            UserInfoDto userStatData = getUserStatData(userInfoDto.getUserId());

            userInfoDto.setCommentNum(userStatData.getCommentNum());
            userInfoDto.setShareNum(userStatData.getShareNum());
            userInfoDto.setImagineNum(userStatData.getImagineNum());
        }
        return userinfoDtoList;
    }

    @Override
    public UserInfoDto getUserStatData(Long userId) throws Exception {
        return userInfoMapper.getUserStatData(userId);
    }

    @Override
    public void deleteUser(Long userId) throws Exception {
        userInfoMapper.deleteByPrimaryKey(userId);
    }

    @Override
    public void modifyUserInfo(UserInfo userInfo) throws Exception {
        userInfoMapper.updateByPrimaryKeySelective(userInfo);
    }
}
